package ru.mipt.sport.gui.registry;

import javax.persistence.EntityManager;
import javax.swing.event.TableModelEvent;
import ru.mipt.sport.gui.model.SportsSpecializationsTableModel;
import ru.mipt.sport.model.interfaces.SportSpecialization;
import ru.mipt.sport.utils.DBUtils;

/**
 *
 * @author Anton Danshin <anton.danshin@frtk.ru>
 */
public class SportsWindow extends javax.swing.JFrame {

    private final DBUtils db = DBUtils.getInstance();

    /**
     * Creates new form SportsWindow
     */
    public SportsWindow() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        sportSpecializationsTable = new javax.swing.JTable();
        addSportButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sports");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        sportSpecializationsTable.setModel(new SportsSpecializationsTableModel());
        sportSpecializationsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                sportSpecializationsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(sportSpecializationsTable);

        addSportButton.setText("Add Sport...");
        addSportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addSportButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(addSportButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addSportButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addSportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSportButtonActionPerformed
        AddSportDialog dlg = new AddSportDialog(this, true, null);
        dlg.setVisible(true);
        if (dlg.getReturnStatus() == AddSportDialog.RET_OK) {
            synchronized (db) {
                try {
                    db.getEntityManager(true).merge(dlg.getSport());
                    db.commit();
                } catch (Exception ex) {
                    db.rollback();
                }
            }
            SportsSpecializationsTableModel model = (SportsSpecializationsTableModel) sportSpecializationsTable.getModel();
            model.refresh();
            sportSpecializationsTable.tableChanged(new TableModelEvent(model));
        }


    }//GEN-LAST:event_addSportButtonActionPerformed

    private void sportSpecializationsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sportSpecializationsTableMouseClicked
        if (evt != null && evt.getClickCount() < 2) {
            return;
        }
        SportsSpecializationsTableModel model = (SportsSpecializationsTableModel) sportSpecializationsTable.getModel();
        if (sportSpecializationsTable.getSelectedRow() < 0) {
            return;
        }
        SportSpecialization person = model.getItemAt(sportSpecializationsTable.getSelectedRow());
        AddSportDialog dlg = new AddSportDialog(this, true, person);
        dlg.setVisible(true);
        if (dlg.getReturnStatus() == AddPersonDialog.RET_OK) {
            SportSpecialization s = dlg.getSport();
            if (s == null) {
                return;
            }
            synchronized (db) {
                try {
                    EntityManager em = db.getEntityManager(true);
                    em.merge(s);
                    db.commit();
                } catch (Exception ex) {
                    db.rollback();
                }
            }
            model.refresh();
            sportSpecializationsTable.tableChanged(new TableModelEvent(model));
        }
    }//GEN-LAST:event_sportSpecializationsTableMouseClicked

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        db.close();
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SportsWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SportsWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SportsWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SportsWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SportsWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addSportButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable sportSpecializationsTable;
    // End of variables declaration//GEN-END:variables
}
